#!/bin/bash

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# 🚀 服务管理脚本 - 服务器端使用
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置
SERVER_DIR="/root/internalNetBridge/server"
SERVER_BIN="$SERVER_DIR/bin/server"
LOG_FILE="$SERVER_DIR/logs/server.log"
PID_FILE="$SERVER_DIR/logs/server.pid"

# 切换到服务目录
cd "$SERVER_DIR" || exit 1

# 函数：获取服务PID
get_pid() {
    if [ -f "$PID_FILE" ]; then
        cat "$PID_FILE"
    else
        pgrep -f "bin/server" | head -1
    fi
}

# 函数：检查服务是否运行
is_running() {
    local pid=$(get_pid)
    if [ -n "$pid" ] && ps -p "$pid" > /dev/null 2>&1; then
        return 0
    else
        return 1
    fi
}

# 函数：启动服务
start_service() {
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${GREEN}🚀 启动服务${NC}"
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    if is_running; then
        echo -e "${YELLOW}⚠️  服务已在运行中 (PID: $(get_pid))${NC}"
        return 0
    fi
    
    # 检查并释放端口
    echo "🔍 检查端口占用情况..."
    
    # 检查8080端口
    if netstat -tlnp 2>/dev/null | grep -q ":8080 " || ss -tlnp 2>/dev/null | grep -q ":8080 "; then
        echo -e "${YELLOW}⚠️  8080端口被占用，正在释放...${NC}"
        local pid_8080=$(netstat -tlnp 2>/dev/null | grep ":8080 " | awk '{print $7}' | cut -d'/' -f1 | head -1)
        if [ -z "$pid_8080" ]; then
            pid_8080=$(ss -tlnp 2>/dev/null | grep ":8080 " | grep -oP 'pid=\K[0-9]+' | head -1)
        fi
        if [ -n "$pid_8080" ]; then
            kill $pid_8080 2>/dev/null || kill -9 $pid_8080 2>/dev/null || true
            sleep 1
            echo "✅ 8080端口已释放"
        fi
    fi
    
    # 检查8088端口
    if netstat -tlnp 2>/dev/null | grep -q ":8088 " || ss -tlnp 2>/dev/null | grep -q ":8088 "; then
        echo -e "${YELLOW}⚠️  8088端口被占用，正在释放...${NC}"
        local pid_8088=$(netstat -tlnp 2>/dev/null | grep ":8088 " | awk '{print $7}' | cut -d'/' -f1 | head -1)
        if [ -z "$pid_8088" ]; then
            pid_8088=$(ss -tlnp 2>/dev/null | grep ":8088 " | grep -oP 'pid=\K[0-9]+' | head -1)
        fi
        if [ -n "$pid_8088" ]; then
            kill $pid_8088 2>/dev/null || kill -9 $pid_8088 2>/dev/null || true
            sleep 1
            echo "✅ 8088端口已释放"
        fi
    fi
    
    # 检查4433端口
    if netstat -tlnp 2>/dev/null | grep -q ":4433 " || ss -tlnp 2>/dev/null | grep -q ":4433 "; then
        echo -e "${YELLOW}⚠️  4433端口被占用，正在释放...${NC}"
        local pid_4433=$(netstat -tlnp 2>/dev/null | grep ":4433 " | awk '{print $7}' | cut -d'/' -f1 | head -1)
        if [ -z "$pid_4433" ]; then
            pid_4433=$(ss -tlnp 2>/dev/null | grep ":4433 " | grep -oP 'pid=\K[0-9]+' | head -1)
        fi
        if [ -n "$pid_4433" ]; then
            kill $pid_4433 2>/dev/null || kill -9 $pid_4433 2>/dev/null || true
            sleep 1
            echo "✅ 4433端口已释放"
        fi
    fi
    
    # 确保日志目录存在
    mkdir -p logs
    
    # 设置Go环境变量
    export PATH=$PATH:/usr/local/go/bin
    export GOPATH=/root/go
    export GOPROXY=https://goproxy.cn,direct
    
    echo ""
    echo "🚀 启动服务..."
    
    # 启动服务
    nohup "$SERVER_BIN" > "$LOG_FILE" 2>&1 &
    local pid=$!
    echo $pid > "$PID_FILE"
    
    sleep 3
    
    if is_running; then
        echo -e "${GREEN}✅ 服务启动成功${NC}"
        echo -e "   PID: $pid"
        echo -e "   日志: $LOG_FILE"
        
        # 显示端口监听
        echo ""
        echo "📊 端口监听:"
        netstat -tlnp 2>/dev/null | grep -E ":8080|:8088|:4433" || ss -tlnp 2>/dev/null | grep -E ":8080|:8088|:4433"
    else
        echo -e "${RED}❌ 服务启动失败${NC}"
        echo "查看日志："
        tail -n 20 "$LOG_FILE"
        return 1
    fi
}

# 函数：停止服务
stop_service() {
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${YELLOW}🛑 停止服务${NC}"
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    if ! is_running; then
        echo -e "${YELLOW}⚠️  服务未运行${NC}"
        rm -f "$PID_FILE"
        return 0
    fi
    
    local pid=$(get_pid)
    echo "📍 正在停止服务 (PID: $pid)..."
    
    # 尝试优雅停止
    kill "$pid" 2>/dev/null
    sleep 3
    
    # 检查是否已停止
    if ! is_running; then
        echo -e "${GREEN}✅ 服务已停止${NC}"
        rm -f "$PID_FILE"
        return 0
    fi
    
    # 强制停止
    echo "⚠️  优雅停止失败，强制终止..."
    kill -9 "$pid" 2>/dev/null
    sleep 1
    
    if ! is_running; then
        echo -e "${GREEN}✅ 服务已强制停止${NC}"
        rm -f "$PID_FILE"
    else
        echo -e "${RED}❌ 停止服务失败${NC}"
        return 1
    fi
}

# 函数：重启服务
restart_service() {
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${GREEN}🔄 重启服务${NC}"
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    stop_service
    sleep 2
    start_service
}

# 函数：查看服务状态
status_service() {
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${GREEN}📊 服务状态${NC}"
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    if is_running; then
        local pid=$(get_pid)
        echo -e "${GREEN}✅ 服务运行中${NC}"
        echo ""
        echo "📍 进程信息:"
        ps aux | grep "$pid" | grep -v grep | awk '{print "   PID: "$2"\n   CPU: "$3"%\n   MEM: "$4"%\n   启动时间: "$9"\n   运行时长: "$10}'
        
        echo ""
        echo "📊 端口监听:"
        netstat -tlnp 2>/dev/null | grep -E ":8088|:4433" || ss -tlnp 2>/dev/null | grep -E ":8088|:4433"
        
        echo ""
        echo "📝 最近日志 (最后20行):"
        tail -n 20 "$LOG_FILE"
    else
        echo -e "${RED}❌ 服务未运行${NC}"
        
        if [ -f "$LOG_FILE" ]; then
            echo ""
            echo "📝 最近日志 (最后20行):"
            tail -n 20 "$LOG_FILE"
        fi
    fi
}

# 函数：查看日志
logs_service() {
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${GREEN}📝 查看日志${NC}"
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    if [ ! -f "$LOG_FILE" ]; then
        echo -e "${RED}❌ 日志文件不存在${NC}"
        return 1
    fi
    
    if [ "$1" = "-f" ] || [ "$1" = "--follow" ]; then
        echo "实时查看日志 (Ctrl+C 退出)..."
        tail -f "$LOG_FILE"
    else
        local lines=${1:-50}
        echo "显示最近 $lines 行日志..."
        tail -n "$lines" "$LOG_FILE"
    fi
}

# 函数：编译服务
build_service() {
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${GREEN}🔨 编译服务${NC}"
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    # 设置Go环境变量
    export PATH=$PATH:/usr/local/go/bin
    export GOPATH=/root/go
    export GOPROXY=https://goproxy.cn,direct
    
    echo "📦 下载依赖..."
    go mod download
    
    echo "🔨 编译中..."
    go build -o bin/server main.go
    
    if [ -f "bin/server" ]; then
        echo -e "${GREEN}✅ 编译成功${NC}"
        ls -lh bin/server
    else
        echo -e "${RED}❌ 编译失败${NC}"
        return 1
    fi
}

# 函数：显示帮助
show_help() {
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${GREEN}🚀 服务管理脚本${NC}"
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""
    echo "用法: $0 {start|stop|restart|status|logs|build|help}"
    echo ""
    echo "命令说明:"
    echo "  start          启动服务"
    echo "  stop           停止服务"
    echo "  restart        重启服务"
    echo "  status         查看服务状态"
    echo "  logs [行数]    查看日志（默认50行）"
    echo "  logs -f        实时查看日志"
    echo "  build          编译服务"
    echo "  help           显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 start           # 启动服务"
    echo "  $0 logs 100        # 查看最近100行日志"
    echo "  $0 logs -f         # 实时查看日志"
    echo ""
}

# 主程序
case "$1" in
    start)
        start_service
        ;;
    stop)
        stop_service
        ;;
    restart)
        restart_service
        ;;
    status)
        status_service
        ;;
    logs)
        logs_service "$2"
        ;;
    build)
        build_service
        ;;
    help|--help|-h)
        show_help
        ;;
    *)
        show_help
        exit 1
        ;;
esac

exit 0

